/**
 * Express.js 数据持久化存储——mysql示例
 */

//导入Express模块
const express = require("express");
//创建Express应用
const app = express();
//Express http服务端口
const port = 3001;

//导入mysql数据访问模型
const db = require("./db/11_test_db");

//获取指定id的书籍信息
app.get("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        db.query("select * from books where id=?",[bookId]).then((result)=>{
            console.log(result);
            res.json(result);
        }).catch((error)=>{
            console.error(error);
            res.end();
        })
    }
});

//获取书籍列表
app.get("/",function(req,res,next){
        db.query("select * from books")
        .then((result)=>{
            console.log(result);
            res.json(result);
        }).catch((error)=>{
            console.error(error);
            res.end();
        })
    }
);

//新增书籍
app.get("/:id",function(req,res,next){
    let title = "测试书籍信息" + new Data().toLocaleString();
    db.query("insert into books (title,desription) values (?,?)",[title,"作者：六之",])
    .then(result=>{
        console.log(result.insertId);
        res.json(result);
    }).catch(error=>{
        console.error(error);
        res.end();
    })
}
);

//更新书籍
app.get("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        let title = "测试书籍信息" + new Data().toLocaleString();
        db.query("update books set title=?,description=? where id=?",[title,"作者：吴",booksId]).then((result)=>{
            console.log(result);
            res.json(result);
        }).catch((error)=>{
            console.error(error);
            res.end();
        })
    }
});

//删除书籍
app.get("/:id",function(req,res,next){
    let bookId = parseInt(req.params.id);
    if(Number.isNaN(bookId)){
        next();
    }else{
        db.query("delect from books where id=?",[booksId]).then((result)=>{
            console.log(result);
            res.json(result);
        }).catch((error)=>{
            console.error(error);
            res.end();
        })
    }
});

//启动Express服务
app.listen(port,function(){
    console.log(`MyApp访问地址：http://127.0.0.1:${port}`);
});